<template>
  <el-scrollbar class="h-full">
    <el-form
      ref="formRef"
      v-loading="loading"
      :model="formState"
      :rules="rules"
      class="flex flex-col items-start gap-y-4"
      label-position="top"
    >
      <QuoteCard description="用户端展示的联系方式">
        <div class="grid grid-cols-3 gap-x-14 pr-44 pl-2">
          <el-form-item class="mb-10" prop="phone">
            <template #label>
              <div class="text-black">电话：</div>
            </template>
            <el-input
              v-model="formState.phone"
              resize="none"
              type="textarea"
              :rows="5"
              placeholder="请输入电话（一行一个，最多5个）"
            ></el-input>
          </el-form-item>
          <el-form-item class="mb-10" prop="email">
            <template #label>
              <div class="text-black">邮箱：</div>
            </template>
            <el-input
              v-model="formState.email"
              resize="none"
              type="textarea"
              placeholder="请输入邮箱（一行一个，最多5个）"
            ></el-input>
          </el-form-item>
          <el-form-item class="mb-10" prop="qq">
            <template #label>
              <div class="text-black">QQ：</div>
            </template>
            <el-input
              v-model="formState.qq"
              resize="none"
              type="textarea"
              placeholder="请输入QQ（一行一个，最多5个）"
            ></el-input>
          </el-form-item>
          <el-form-item prop="telegram">
            <template #label>
              <div class="text-black">Telegram：</div>
            </template>
            <el-input
              v-model="formState.telegram"
              resize="none"
              type="textarea"
              :placeholder="`请输入Telegram分享地址（一行一个，最多5个）格式示例：
https://t.me/zhelishiID`"
            ></el-input>
          </el-form-item>
          <el-form-item prop="skype">
            <template #label>
              <div class="text-black">Skype：</div>
            </template>
            <el-input
              v-model="formState.skype"
              resize="none"
              type="textarea"
              :placeholder="`请输入Skype分享地址（一行一个，最多5个）格式示例：
https://join.skype.com/invite/ZHELISHIID`"
            ></el-input>
          </el-form-item>
        </div>
        <div class="-ml-2">
          <el-divider />
          <el-button type="primary" @click="handleSave">保存配置</el-button>
        </div>
      </QuoteCard>
    </el-form>
  </el-scrollbar>
</template>

<script setup lang="ts">
import type { FormInstance, FormItemRule } from 'element-plus'

import { QuoteCard } from '@/components/application'
import ToastUtils from '@/utils/toast'

import { contactValidate } from './contactValidate'

const formRef = ref<FormInstance>()
const loading = ref(false)
const formState = reactive({
  phone: '',
  email: '',
  qq: '',
  telegram: '',
  skype: ''
})

const validator = (rule: any, value: string) => {
  if (!value) return true

  const arr = value.split(/\n/) as string[]
  if (arr.length > 5) {
    return new Error('最多只能输入5个')
  }
  // if (arr.some(v => v?.length > 30)) {
  //   return new Error('一行最大输入30字符')
  // }

  const validate = contactValidate[rule.field as keyof typeof contactValidate]
  if (!validate) {
    console.error(`未找到${rule.field}的验证规则`)
    return true
  }

  if (arr.length) {
    for (const item of arr) {
      const { reg, error } = validate
      if (!reg.test(item)) {
        return new Error(error)
      }
    }
  }

  return true
}

const rules: Record<string, FormItemRule[]> = {
  phone: [{ validator, trigger: 'blur' }],
  email: [{ validator, trigger: 'blur' }],
  qq: [{ validator, trigger: 'blur' }],
  telegram: [{ validator, trigger: 'blur' }],
  skype: [{ validator, trigger: 'blur' }]
}

const filterEmpty = (arr: string[]) => {
  return arr.filter(item => item.length)
}

onMounted(() => {
  loading.value = true
  configInfoApi({})
    .then(res => {
      const keys = Object.keys(formState)
      keys.forEach(key => {
        const arr = res.website_contact![key] as string[]
        formState[key] = filterEmpty(arr).join('\n')
      })
    })
    .finally(() => {
      loading.value = false
    })
})

const handleSave = async () => {
  await formRef.value?.validate()
  loading.value = true
  const data = {}
  const keys = Object.keys(formState)
  keys.forEach(key => {
    Reflect.set(data, key, getTrimValue(formState[key]))
  })
  editConfigApi({
    website_contact: data
  })
    .then(() => {
      ToastUtils.success('修改成功')
    })
    .finally(() => {
      loading.value = false
    })
}
</script>

<style lang="scss" scoped>
.el-textarea {
  :deep(.el-textarea__inner) {
    height: 120px;
  }
}
</style>
